﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AiXiu.Model;
using AiXiu.BLL;
using AiXiu.Common;

namespace AiXiu.WebSite
{
    public partial class Update : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //页面第一次加载
            if (!IsPostBack)
            {
                //读取用户资料
                TBUsers users = IdentityManager.ReadUser();

                //获取用户信息
                txtUserName.Text = users.NickName;
                drSex.SelectedIndex = users.Sex;
                txtBirthday.Text = users.Birthday.HasValue ? users.Birthday.Value.ToString("yyyy-MM-dd") : "";
                hidAddress.Value = users.Address;
                hidHobby.Value = users.Hobby;   
            }
        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            // 读取信息
            TBUsers user = IdentityManager.ReadUser();
            user.NickName = this.txtUserName.Text;
            user.Sex = this.drSex.SelectedIndex;
            if (!string.IsNullOrEmpty(this.txtBirthday.Text))
            {
                user.Birthday = DateTime.Parse(this.txtBirthday.Text);
            }
            user.Address = hidAddress.Value;
            user.Hobby = hidHobby.Value;
            // 更新资料
            UserBLL userBLL = new UserBLL();
            OperResult<TBUsers> editResult = userBLL.UpdateUserInfo(user);
            if (editResult.StatusCode == StatusCode.Succeed)
            {
                TBUsers userEntity = editResult.ReadResult();
                // 读取缓存用户资料
                TBUsers userCookie = IdentityManager.ReadUser();
                if (userCookie == null)
                {
                    this.Alert("cookienull", "缓存读取出错！");
                }
                // 更新用户缓存信息
                userCookie.NickName = userEntity.NickName;
                userCookie.Sex = userEntity.Sex;
                userCookie.Birthday = userEntity.Birthday;
                userCookie.Address = userEntity.Address;
                userCookie.Hobby = userEntity.Hobby;
                // 缓存用户资料
                IdentityManager.SaveUser(userCookie);
                // 跳转到个人页
                Response.Redirect("MyInfo.aspx");
            }
            else
            {
                this.Alert("editerror", editResult.Message);
            }
        }
    }
}